<template>
    <theme-box title="角色添加">
        <div class="col-sm-6">
            <form method="post" action="" class="form-inline" v-el:form @submit.prevent>
                <div class="box-body">
                    <form-group title="商户号" :required="true" style="display: flex">
                        <select name="mchtId" class="form-control" v-model="mchtIdValue" id="mchtId"
                                style="width: 450px;min-width: 50%;">
                            <option v-for="mcht in mchtList" :value="mcht.value">
                                {{mcht.key}}
                            </option>
                        </select>
                    </form-group>
                    <form-input name="roleName" :required="true" title="角色名称" styles="width: 450px"  style="display: flex"></form-input>
                    <form-select name="roleTpe" title="角色类型" :value.sync="roleTypeValue" :options="roleTypeOptions"
                                 :required="true" styles="width: 450px"  style="display: flex"></form-select>
                    <form-input name="roleDsc" title="角色描述" styles="width: 450px" style="display: flex"></form-input>
                </div>
                <!-- /.box-body -->
                <div class="wizard-buttons">
                    <div class="row" style="min-width: 560px;max-width: 720px;">
                        <div class="col-sm-11">
                            <div class="text-center">
                                <v-button theme="primary" @click="formSubmit" class="col-sm-offset-1 pull-right">确认
                                </v-button>
                                <v-button class="col-sm-offset-1 pull-left" @click="reset">重置</v-button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.box-footer -->
            </form>
        </div>
        <div class="col-sm-6">
            <div class="treeview list-group">
                <form v-el:treeform>
                    <tree-item :tree.sync="tree" v-ref:tree></tree-item>
                </form>
            </div>
        </div>
    </theme-box>
</template>

<style lang="css" scoped>
    .treeview input[type="checkbox"] {
        width: 12px;
        margin-right: 6px;
    }

    .treeview .list-group-item {
        padding: 10px 15px;
    }

    .wizard-buttons {
        background-color: #fff;
        border-top: none
    }
</style>
<script>
    import {
        sketch
    } from 'lib/permission.js'
    import Item from './item.vue';

    var serialize = require('form-serialize');
    export default {
        data: () => ({
            num: 0,
            mchtIdValue: "",
            roleTypeValue: "",
            value: "",
            mchtList: [],
            tree: [],
            roleTypeOptions: [
                {key: "系统操作员", value: "system"},
                {key: "商户管理员", value: "mchtmanager"},
                {key: "商户操作员", value: "mchtopr"},
            ]
        }),
        components: {
            'tree-item': Item
        },
        watch: {
            mchtIdValue (v) {
                if (v == "10000000") {
                    this.roleTypeOptions = [
                        {key: "系统操作员", value: "system"}
                    ]
                } else {
                    this.roleTypeOptions = [
                        {key: "商户管理员", value: "mchtmanager"},
                        {key: "商户操作员", value: "mchtopr"}
                    ]
                }
                this.roleTypeValue = this.roleTypeOptions[0].value;
                this.num = 1;
                this.getRoleList()
            },
            roleTypeValue (v) {
                if (this.num > 0) {
                    this.getRoleList()
                }
            },
        },
        methods: {
            reset () {
                $("label.error").remove();
                this.$els.form.reset();
                this.roleTypeOptions = [
                    {key: "系统操作员", value: "system"}
                ];
                this.$refs.tree.deselect();
                this.$refs.tree.initExpand();
            },
            assign (json) {
                let self = this;
                let cake = json.map((player, index) => {
                    let text = player.key;
                    let value = player.value;
                    if (player.hasOwnProperty("child")) {
                        let children = self.assign(player.child);
                        return {
                            children,
                            text,
                            value
                        }
                    } else {
                        return {
                            text,
                            value
                        }
                    }
                });
                return cake;
            },
            getMcht (data) {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: "/api/v2" + projectName_Url + "/list/mcht/role/" + mchtId,
                    method: "GET"
                }).then(response => {
                    let list = response.content.info;
                    self.$set("mchtList", list);
                    self.mchtIdValue = list[0].value
                }, error => {
                });
            },
            getRoleList () {
                let self = this;
                this.$http({
                    url: httpProject + '/api/v1' + projectName_Url + '/roleList/add/' + self.roleTypeValue + '/' + self.mchtIdValue,
                    method: 'GET'
                }).then(response => {
                    let json = response.body.content;
                    let data = sketch(json.info)
                    let tree = self.assign(data);
                    self.$set('tree', tree);
                    self.$refs.tree.$set('tree', tree)
                    self.$nextTick(() => {
                        if (window.tree) {
                            $(".tree").children().remove()
                        }
                        self.$refs.tree.init();
                        self.$refs.tree.initExpand();
                    });
                }, error => {
                });
            },
            formSubmit () {
                let self = this;
                let form = this.$els.form;

                if (!$(form).valid()) {
                    return false;
                }
                $(form).find("input").each(function () {
                    $(this).val($.trim($(this).val()));
                });

                let arr = self.$refs.tree.get();
                if (arr.length == 0) {
                    let data = {
                        title: "操作提示",
                        content: "必须分配角色权限"
                    }
                    Midway.alert(data);
                    return false;
                }

                let _data = serialize(form, {
                    hash: true
                });

                _data.roleList = arr.join(",");
                self.submit(_data);
            },
            submit (data) {
                let self = this;
                self.$post({
                    url: '/api/v1' + projectName_Url + '/plat/role/add',
                    data
                }).then(response => {
                    let data = {
                        title: "操作成功",
                        content: "是否进入角色列表查看?"
                    }
                    self.reset();
                    Midway.confirm(data).then(function () {
                        self.$route.router.go('/role/list');
                    })
                }, error => {
                });
            }
        },
        beforeCompile () {
            // this.getRoleList();
        },
        ready: function () {

            let self = this;

            self.getMcht();
            //商户号改变事件
            $("select[name='mchtId']").change(function () {
                if ($("select[name='mchtId']").val() == '10000000') {
                    self.roleTypeOptions = [
                        {key: "系统操作员", value: "system"}
                    ]
                } else {
                    self.roleTypeOptions = [
                        {key: "商户管理员", value: "mchtmanager"},
                        {key: "商户操作员", value: "mchtopr"}
                    ]
                }
            })
            $(this.$els.form).validate({
                rules: {
                    mchtId: {
                        required: true
                    },
                    roleName: {
                        required: true,
                        maxlength: 12
                    },
                    roleTpe: {
                        required: true,
                        maxlength: 11
                    },
                },
                messages: {
                    roleName: {
                        required: "角色名称不能为空",
                        maxlength: "角色名称不超过12位"
                    },
                    roleDes: {
                        maxlength: "角色名称不超过30位"
                    }
                }
            });
        }
    }
</script>
